package com.bana.sys.service;

import com.bana.sys.code.DatabaseResult;
import com.bana.sys.dao.*;
import com.bana.sys.model.*;
import com.bana.sys.utils.Encryption;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

@Service
public class UserService
{
    @Resource
    private UserRoleDAO userRoleDAO;
    @Resource
    private UserDAO userDAO;
    @Resource
    private RoleDAO roleDAO;
    @Resource
    private FunctionDAO functionDAO;
    @Resource
    private DepartmentService departmentService;

    /**
     * 添加用户
     * @param user 用户
     * @return 包含新增用户的主键
     */
    @Transactional
    public int insertUser(User user)
    {
        if(userDAO.getUserCountById(user.getYhmc())==0) {
            user.setDlmm(Encryption.md5Encrypt(user.getDlmm()));
            userDAO.insertUser(user);
            for (Role role : user.getRoles()) {
                UserRole userRole = new UserRole();
                userRole.setYhmc(user.getYhmc());
                userRole.setJsbm(role.getJsbm());
                userRoleDAO.insertUserRole(userRole);
            }
            return DatabaseResult.Success;
        }else{
            return DatabaseResult.UserRepeat;
        }
    }

    /**
     * 更新用户
     * @param user 更新用户
     */
    @Transactional
    public void updateUser(User user)
    {
        userRoleDAO.deleteUserRoles(0,user.getYhmc());
        userDAO.updateUser(user);
        for(Role role:user.getRoles())
        {
            UserRole userRole=new UserRole();
            userRole.setYhmc(user.getYhmc());
            userRole.setJsbm(role.getJsbm());
            userRoleDAO.insertUserRole(userRole);
        }
    }

    /**
     * 删除用户
     * @param yhmc 用户名称
     */
    @Transactional
    public void deleteUser(String yhmc)
    {
        if("admin".equals(yhmc))
        {
            return;
        }
        userDAO.deleteUser(yhmc);
        userRoleDAO.deleteUserRoles(0,yhmc);
    }

    /**
     * 用户更新密码
     * @param user 用户
     * @return 返回true表示更新，返回false表示原密码验证错误
     */
    public boolean updatePasswordByUser(User user)
    {
        User temp=new User();
        temp.setYhmc(user.getYhmc());
        temp.setDlmm(user.getOldDlmm());
        if(validateUser(temp)==null)
        {
            return false;
        }
        else
        {
            user.setYhmc(temp.getYhmc());
            user.setDlmm(Encryption.md5Encrypt(user.getDlmm()));
            userDAO.updatePassword(user);
            return true;
        }
    }

    /**
     * 管理员更新密码
     * @param user 用户
     */
    public void updatePasswordByAdmin(User user)
    {
        user.setDlmm(Encryption.md5Encrypt(user.getDlmm()));
        userDAO.updatePassword(user);
    }

    /**
     * 获取用户信息和功能集合
     * @param yhmc 用户名称
     * @return 用户信息
     */
    public User getUserWithFunctions(String yhmc)
    {
        User user=userDAO.getUser(yhmc);
        fillFunctions(user);
        return user;
    }


    /**
     * 获取用户集合
     * @param parameter 用户搜索参数
     * @return 用户集合
     */
    public List<User> getUsersWithFunctions(UserPageParameter parameter)
    {
        List<User> users = userDAO.getUsers(parameter);
        for(User user:users)
        {
            fillFunctions(user);
        }
        return users;
    }

    /**
     * 填充用户功能集合
     * @param user 用户
     */
    private void fillFunctions(User user)
    {
        if(user.getYhmc().equals("admin"))
        {
            user.setFunctions(functionDAO.getFunctions(new FunctionPageParameter()));
        }
        else
        {
            RolePageParameter rolePageParameter=new RolePageParameter();
            rolePageParameter.setYhmc(user.getYhmc());
            user.setRoles(roleDAO.getRoles(rolePageParameter));

            Map<String,Function> functionMap=new HashMap<>();
            for(Role role:user.getRoles()){
                FunctionPageParameter functionPageParameter=new FunctionPageParameter();
                functionPageParameter.setJsbm(role.getJsbm());
                for(Function function:functionDAO.getFunctions(functionPageParameter))
                {
                    functionMap.put(function.getGnbm(),function);
                }
            }
            List<Function> functions=new ArrayList<>();
            for(Map.Entry<String,Function> function:functionMap.entrySet())
            {
                functions.add(function.getValue());
            }
            Collections.sort(functions, Comparator.comparing(Function::getGnbm));
            user.setFunctions(functions);
        }
    }

    /**
     * 填充user的departmentPath
     * @param user
     */
    public void fillDepartment(User user)
    {
        if(user.getJgbm()==Department.All)
        {
            user.setDepartmentPath(Department.AllTag);
        }
        else if(user.getJgbm()==Department.None)
        {
            user.setDepartmentPath(Department.NoneTag);
        }
        else
        {
            user.setDepartmentPath(departmentService.getDepartmentPath(user.getJgbm()));
        }
    }

    /**
     * 验证用户密码
     * @param user 用户
     * @return 验证成功返回true
     */
    public User validateUser(User user)
    {
        User temp=userDAO.getUser(user.getYhmc());
        if(temp==null)
        {
            return null;
        }
        else
        {
           if(temp.getDlmm().equals(Encryption.md5Encrypt(user.getDlmm()))
                   ||temp.getDlmm().equals(user.getDlmm()))
           {
               return temp;
           }
           else
           {
               return null;
           }
        }
    }
}
